package com.huarun.module.toilet.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.*;
import com.huarun.common.util.http.HttpParamers;
import com.huarun.common.util.http.HttpService;
import com.huarun.module.toilet.bean.ToiletPit;
import com.huarun.module.toilet.service.ToiletService;
import com.huarun.module.webapi.WelingService;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedReader;
import java.security.Key;
import java.security.PublicKey;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/wx/toilet"})
public class ToiletController extends BaseController {

    @Resource
    private ToiletService toiletService;
    @Autowired
    private WelingService welingService;

    @ApiOperation(value = "获取所有厕所", notes = "厕所列表")
    @RequestMapping(value = {"/list"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    @ResponseBody
    public Object Project_WorkOrders1() throws Exception {
//    long time = System.currentTimeMillis();
//    String url = "https://crland-api.ibuilding.qcloud.com";
//    params.put("Action", "ListDevices");
//    params.put("PageSize", Integer.valueOf(20));
//    params.put("PageNum", Integer.valueOf(0));
//    params.put("ProjectID", Integer.valueOf(102));
//    params.put("Region", "shenzhen");
//    params.put("Timestamp", Long.valueOf(time));
//
//    params.put("Filter", "{\"DeviceType\":[\"20\"]}");
//    params.put("Nonce", "abc");
//    params.put("SecretId", "5c496e27f73c970e8e19e07d");
//    params.put("Version", "1.0");
//    String sort = Md5SignUtil.sort(params);
//    String genHMAC = Md5SignUtil.genHMAC(sort, "kYTMVliS4GaXLmU9FrXC8lOWR5JYiVnU");
//    params.put("Signature", genHMAC);
        String host = Constant.WELINK_LOGIN_HOST;
        String toiletUrl = "/space/datahub/common/v1.0/current/getDeviceStatus";
        HttpParamers paramers = HttpParamers.httpGetParamers();
        paramers.addParam("token", welingService.getToken());
        paramers.addParam("poiCode", "w0725000");//对象类型分类编码
        HttpService httpService = new HttpService(host);
        String toiletReturn = httpService.service(toiletUrl, paramers);
        JSONObject jsonReturn = JSONObject.parseObject(toiletReturn);
        log.info("厕所数据: " + jsonReturn.toJSONString());
        return jsonReturn;
    }

    @ApiOperation(value = "获取所有厕所蹲位", notes = "厕所蹲位列表")
    @RequestMapping(value = {"/pits"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    @ResponseBody
    public ResponseMessage<Object> Project_WorkOrders2(HttpServletRequest request, String DeviceID) throws Exception {
        ResponseMessage rm = new ResponseMessage();
        Map params = new HashMap();
        try {
            ToiletPit pit = new ToiletPit();
            if (DeviceID.equals("102000000000001"))
                pit.setSex(Integer.valueOf(0));
            else if (DeviceID.equals("102000000000002")) {
                pit.setSex(Integer.valueOf(1));
            }
            Map map = new HashMap();
            map.put("sex", pit.getSex());
            List findList = this.toiletService.findList(map);
            if (findList.size() == 0) {
                long time = System.currentTimeMillis() / 1000L;
                String url = "https://crland-api.ibuilding.qcloud.com";
                params.put("Action", "GetShadow");
                params.put("DeviceID", DeviceID);
                params.put("Region", "shenzhen");
                params.put("Timestamp", Long.valueOf(time));
                params.put("Nonce", "abc");
                params.put("SecretId", "5c496e27f73c970e8e19e07d");
                params.put("Version", "1.0");
                String sort = Md5SignUtil.sort(params);
                String genHMAC = Md5SignUtil.genHMAC(sort, "kYTMVliS4GaXLmU9FrXC8lOWR5JYiVnU");
                params.put("Signature", genHMAC);

                JSONObject json = JSONObject.parseObject(JSON.toJSONString(params));
                JSONObject obj = HttpRequestUtils.httpPost(url, json);
                Map<String, Object> parseObject;
                String data;
                if (obj.getInteger("Code").intValue() == 0) {
                    parseObject = new HashMap();

                    if (DeviceID.equals("102000000000001")) {
                        data = obj.getJSONObject("Data").getJSONObject("Properties").getJSONObject("MalePits")
                                .getJSONObject("dataType")
                                .getString("value");
                        parseObject = (Map) JSONObject.parseObject(data, Map.class);
                        pit.setSex(Integer.valueOf(0));
                    } else if (DeviceID.equals("102000000000002")) {
                        data = obj.getJSONObject("Data").getJSONObject("Properties").getJSONObject("FemalePits")
                                .getJSONObject("dataType")
                                .getString("value");
                        parseObject = (Map) JSONObject.parseObject(data, Map.class);
                        pit.setSex(Integer.valueOf(1));
                    }

                    for (String key : parseObject.keySet()) {
                        String value = parseObject.get(key).toString();
                        pit.setPitname(key);
                        pit.setPitssatus(value);
                        this.toiletService.save(pit);
                    }

                }

                rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
                rm.setData("插入数据成功");
            }

            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
            rm.setData(findList);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("程序异常！");
            e.printStackTrace();
        }

        return rm;
    }

    @ApiOperation(value = "更新时间", notes = "更新时间")
    @RequestMapping(value = {"/updateTime"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> Project_WorkOrders3(HttpServletRequest request) throws Exception {
        this.log.info("======接收到厕所状态推送：time:" + System.currentTimeMillis());
        ResponseMessage rm = new ResponseMessage();
        ToiletPit pit = new ToiletPit();
        Map<String, Object> map = new HashMap();
        try {
            int flag = 0;
            BufferedReader br = request.getReader();
            String wholeStr = "";
            String str;
            while ((str = br.readLine()) != null) {
                wholeStr = wholeStr + str;
            }
            this.log.info("======接收到厕所状态推送：接收内容为:" + wholeStr);
            System.out.println(wholeStr);
            JSONObject parseObject = JSONObject.parseObject(wholeStr);
            String key = parseObject.get("key").toString();
            String content = parseObject.get("content").toString();
            PublicKey publicKey = Crypt.getPublicKey(Crypt.publicKeyString);

            byte[] keyBytes = Base64.getDecoder().decode(key);
            String keyTimeString = new String(Crypt.decryptRSA(keyBytes, publicKey));
            String keyString = keyTimeString.substring(0, keyTimeString.length() - 13);
            Key aesKey = Crypt.getSecretKey(keyString);
            System.out.printf("get key string %s\n", new Object[]{keyTimeString});
            System.out.printf("%s", new Object[]{keyString});

            byte[] msgBytes = Base64.getDecoder().decode(content);
            String plaintext = new String(Crypt.decryptAES(msgBytes, aesKey));
            this.log.info("======接收到厕所状态推送：消息明文为:" + plaintext);
            JSONObject json = JSONObject.parseObject(plaintext);
            JSONObject propertiesInfo = json.getJSONObject("properties_info");

            String deviceId = json.getJSONObject("device_info").getJSONObject("src_device").getString("device_id");
            String femalePits;
            if (deviceId.equals("102000000000001")) {
                String malePits = propertiesInfo.getString("MalePits");
                map = (Map) JSONObject.parseObject(malePits, Map.class);
            } else if (deviceId.equals("102000000000002")) {
                femalePits = propertiesInfo.getString("FemalePits");
                map = (Map) JSONObject.parseObject(femalePits, Map.class);
            }

            for (String pitname : map.keySet()) {
                String pitssatus = map.get(pitname).toString();
                if (pitssatus.equals("1")) {
                    long newTime = new Date().getTime() / 1000L;
                    pit.setPitssatus("1");
                    pit.setLasttime(Long.valueOf(newTime));
                } else if (pitssatus.equals("0")) {
                    pit.setPitssatus("0");
                    pit.setLasttime(null);
                }
                pit.setPitname(pitname);
                flag = this.toiletService.update(pit);
            }

            if (flag > 0) {
                this.log.info("======接收到厕所状态推送：更新成功！");
                rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
                rm.setData("更新成功");
            } else {
                this.log.info("======接收到厕所状态推送：更新失败！");
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
                rm.setData("更新失败");
            }
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("======接收到厕所状态推送：程序异常！");
            e.printStackTrace();
        }

        return rm;
    }
}
